package com.wlbx.agent.ui.activity;

import static android.widget.PopupWindow.INPUT_METHOD_NEEDED;

import android.content.Intent;
import android.os.Handler;
import android.os.StrictMode;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.orhanobut.logger.Logger;
import com.wlbx.agent.R;
import com.wlbx.agent.base.BaseActivity;
import com.wlbx.agent.global.AccountManager;
import com.wlbx.agent.global.Constant;
import com.wlbx.agent.net.RequestManager;
import com.wlbx.agent.net.RetrofitCallBack;
import com.wlbx.agent.net.RetrofitRequestInterface;

import butterknife.BindView;
import butterknife.OnClick;

public class ChangePhoneActivity extends BaseActivity {
    private static final String TAG = "ChangePhoneActivity";

    @BindView(R.id.tv_layout_top_back_title)
    TextView mTitleTV;
    @BindView(R.id.iv_layout_top_back)
    ImageView mBackIV;
    @BindView(R.id.bt_submit)
    Button bt_submit;
    @BindView(R.id.et_phone)
    EditText et_phone;
    //前页面传入验证码
    private String validCode = "";
    private int requestCode = 100;
    private PopupWindow mPopuptipWindow;

    @Override
    protected int getContentViewId() {
        return R.layout.activity_changephone;
    }

    @Override
    public void initData() {
        StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
                .detectNetwork().penaltyLog().build());
        StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
                .detectLeakedSqlLiteObjects().penaltyLog().penaltyDeath().build());
        validCode = getIntent().getStringExtra("validCode");
        mTitleTV.setText("修改手机号");
        et_phone.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }
            @Override
            public void afterTextChanged(Editable s) {
                if(et_phone.getText().toString().length()==11){
                    bt_submit.setBackgroundDrawable(getResources().getDrawable(R.drawable.bt_en));
                }else{
                    bt_submit.setBackgroundDrawable(getResources().getDrawable(R.drawable.bt_dis));
                }
            }
        });
        checkValid(validCode);
    }

    @Override
    public void initEvent() {}

    @OnClick({R.id.iv_layout_top_back,R.id.bt_submit})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_layout_top_back:
                finish();
                break;
            case R.id.bt_submit:
                getNewValidCode();
                break;
            default:
                break;
        }
    }

    public void getNewValidCode(){
        if(checkPhone()){
            RequestManager
            .mRetrofitManager
            .createRequest(RetrofitRequestInterface.class)
            .getNewPhoneValidCode(et_phone.getText().toString())
            .enqueue(new RetrofitCallBack() {
                @Override
                public void onSuccess(String response) {
                    Logger.i(TAG, response);
                    JSONObject jsonObject = JSON.parseObject(response);
                    String rCode = jsonObject.getString("code");
                    String rMsg  = jsonObject.getString("msg");
                    if("1000".equals(rCode)) {
                        Toast.makeText(mContext,rMsg,Toast.LENGTH_SHORT).show();
                        toCheckValidCode(et_phone.getText().toString());
                    }else{
                        Toast.makeText(mContext,rMsg,Toast.LENGTH_SHORT).show();
                    }
                }
                @Override
                public void onError(Throwable t) {
                    Logger.i(TAG, t.getMessage());
                    Toast.makeText(mContext,"获取验证码失败"+t.getMessage(),Toast.LENGTH_SHORT).show();
                }
            });
        }
    }

    private void toCheckValidCode(String phone){
        Intent intent = new Intent(this,ValidCodeActivity.class);
        intent.putExtra("phone",phone);
        startActivityForResult(intent,requestCode);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode == this.requestCode){
            showPopupTip();
            Handler handler = new Handler();
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    AccountManager.setUserLogin(false);
                    AccountManager.removeSP();
                    toLogin();
                }
            }, 1000);
        }
    }

    private void toLogin(){
        Intent intent = new Intent(this,LoginActivity.class);
        startActivity(intent);
        finish();
    }

    //弹出提示框
    public void showPopupTip(){
        View view = mInflater.inflate(R.layout.pop_tip_change, null);
        mPopuptipWindow = new PopupWindow(view, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
        mPopuptipWindow.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
        mPopuptipWindow.setOutsideTouchable(false);
        mPopuptipWindow.setFocusable(true);
        mPopuptipWindow.getContentView().setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                mPopuptipWindow.setFocusable(false);
                mPopuptipWindow.dismiss();
                return true;
            }
        });
        mPopuptipWindow.showAtLocation(view, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
    }


    private boolean checkPhone() {
        String phone = et_phone.getText().toString();
        if (TextUtils.isEmpty(phone)){
            Toast.makeText(this,"请输入手机号",Toast.LENGTH_SHORT).show();
            return false;
        }
        if (!phone.matches(Constant.PHONE_PATTERN)){
            Toast.makeText(this,"请输入正确的手机号",Toast.LENGTH_SHORT).show();
            return false;
        }
        return true;
    }

    public void checkValid(String code){
        RequestManager
        .mRetrofitManager
        .createRequest(RetrofitRequestInterface.class)
        .checkOldValidCode(code)
        .enqueue(new RetrofitCallBack() {
            @Override
            public void onSuccess(String response) {
                Logger.i(TAG, response);
                JSONObject jsonObject = JSON.parseObject(response);
                String rCode = jsonObject.getString("code");
                String rMsg  = jsonObject.getString("msg");
                if("1000".equals(rCode)) {
                    Toast.makeText(mContext,"验证码校验成功",Toast.LENGTH_SHORT).show();
                }else{
                    Toast.makeText(mContext,rMsg,Toast.LENGTH_SHORT).show();
                }
            }
            @Override
            public void onError(Throwable t) {
                Logger.i(TAG, t.getMessage());
                Toast.makeText(mContext,"校验验证码失败"+t.getMessage(),Toast.LENGTH_SHORT).show();
            }
        });
    }
}